$(function () {
    var query = {},
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $create = $('.btn-create'),
        strHtml = $('#form-template').html();
    var config = {
        query: '/info/query?type1=0&',//分页查询URL,
        'delete': '/info/delete',
    };


    function search(obj, isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return;
            }
        }
        var arg = [];
        query = query_;
        query.timestamp = Date.now();
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        $.get(config.query + arg.join('&'), function (res) {
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$table($.extend(TABLE_SETTING, {
                checkbox: true, // 是否显示复选框
                seqNum: true, // 是否显示序号
                sort: search, //排序回调函数
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                toolbar: '.toolbar',
                enableSetting: true,//允许自定义显示列
                search: function (obj) { //搜索框查询函数
                    search(obj)
                },
                rendered: function () {
                    onClick($('.preview-thubnail'), function (e) {
                        e.stopPropagation();
                        var $json = $(this).data('json');
                        layerPhoto(
                            {
                                "title": "缩略图", //相册标题
                                "id": $json.id, //相册id
                                "start": 0, //初始显示的图片序号，默认0
                                "data": [   //相册包含的图片，数组格式
                                    {
                                        "alt": $json.name,
                                        "pid": $json.id, //图片id
                                        "src": $json.thumbnail, //原图地址
                                        "thumb": $json.thumbnail //缩略图地址
                                    }
                                ]
                            }
                        )
                    });
                    selectGoods({
                        placeholder: '选择分类',
                        name: 'categoryId',
                        url: '/category/list?type1=info',
                        key: 'inf-category',
                        change: function (categoryId) {
                            console.log('categoryId=' + categoryId);
                            search({categoryId: categoryId}, true);
                        }
                    })
                },
                fields: [
                    {
                        name: 'title', label: '标题', enableSort: true, enableSearch: true, filter: function (item) {
                        return '<a target="_blank" href="/info-detail.html?id=' + item.id + '" >' + item.title + '</a>'
                    }
                    },
                    {
                        name: 'categoryId', label: '分类', enableSearch: true, filter: function (item) {
                        return item.category || '';
                    }
                    },
                    {
                        name: 'author', label: '缩略图', filter: function (item) {
                        if (!item.thumbnail)return '';
                        return '<a class="preview-thubnail" data-json=\'' + JSON.stringify(item) + '\' data-url="' + item.thubnail + '" href="javascript:void(0);">查看</a>'
                    }
                    },
                    {name: 'tags', label: '关键字'},
                    {name: 'order1', label: '排序号'},
                    {name: 'author', label: '作者'},
                    {
                        name: 'publish', label: '发布时间', enableSort: true, filter: function (item) {
                        return moment(item.createAt).format('YYYY-MM-DD HH:mm:ss');
                    }
                    },
                ],
                data: res.list || [],
            }));
            var page = res.page;
            pageInit(page, query, search);
        });
    }

    $update.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        window.location.href = './edit.html?id=' + $current.id;
    });
    $delete.unbind('click').on('click', function () {
        var $current = $(this).data('json'), self = this;
        $(self).button('loading');
        if (confirm('确认删除"' + $(this).data('json').title + '"?')) {
            $.post(config['delete'], {id: $current.id}, function (xhr, data) {
                $(self).button('reset');
                if (xhr.code == 200) {
                    fnSuccess('删除成功!');
                    $('tr[id=' + $current.id + ']').remove();
                    // $(self).closest('tr').remove();
                    setTimeout(function () {
                        destroyBtn();
                    }, 0)
                } else {
                    alert('删除失败：' + xhr.error);
                }
            })
        } else {
            $(self).button('reset');
        }
    });
    $create.unbind('click').on('click', function () {
        window.location.href = './edit.html';
    });
    function destroyBtn() {
        $update.data('json', null);
        $delete.data('json', null);
        disableBtn($update);
        disableBtn($delete);
    }

    function createBtn(_this) {
        $update.data('json', ($(_this).data('json')));
        $delete.data('json', ($(_this).data('json')));
        enableBtn($update);
        enableBtn($delete);
    }

    search({}, true);
});